package com.wrb.file.controller;


import com.wrb.file.response.ServerResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by chijr on 16/12/4.
 */
@Slf4j
@RestController
@Api(tags = "文件上传")
@CrossOrigin(origins = "*",methods={RequestMethod.POST, RequestMethod.GET})
@RequestMapping("/file")
public class FileController {
    @Value("${web.upload-path}")
    private String uploadPath;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation(value = "单文件上传")
    public ResponseEntity handleFileUpload(
            HttpServletRequest req,
            @RequestParam("file") MultipartFile file
    ) {
        if (file.isEmpty()) {
            return ServerResponse.error(510,"文件为空");
        }
        try {
            String filePath = this.remoteFilePath(file);
            log.info("path:" + filePath);
            int pos = req.getRequestURL().lastIndexOf("/");
            String urlPath = req.getRequestURL().substring(0,pos);
            urlPath = urlPath+filePath;
            return ServerResponse.success(urlPath);
        } catch (Exception e) {
            return ServerResponse.error(511, "文件错误" + e.getMessage());
        }
    }

    //生成远程的文件名和路径
    private String remoteFilePath(MultipartFile file){
        String filename = file.getOriginalFilename();
        int pos = filename.lastIndexOf(".");
        String extName="";
        if(pos!=-1){
            extName = filename.substring(pos + 1);
        }
        String newFileName = UUID.randomUUID().toString() + "." + extName;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dateString = df.format(new Date());
        String newFilePath = this.uploadPath + "/upload/"+dateString+"/";
        File checkFile =new File(newFilePath);
        if  (!checkFile .exists()  && !checkFile.isDirectory()){
            checkFile.mkdirs();
        }
        String filePath = newFilePath+newFileName;
        byte[] bytes;
        try {
            bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            stream.write(bytes);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/upload/"+dateString+"/"+newFileName;
    }
}
